<template>
  <el-drawer
    title="填写参数"
    size="40%"
    :visible.sync="visible"
    :before-close="onClose"
    :wrapper-closable="true"
    :destroy-on-close="true"
    append-to-body
    custom-class="wxpay-config-drawer"
  >
    <div class="drawer-container">
      <el-form ref="infoFormModel" :model="saveObject" label-position="top" :rules="rules" v-loading="loading">
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="saveObject.state">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="saveObject.remark" placeholder="请输入" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <el-divider>
        <el-tag type="danger">
          {{ saveObject.ifCode }} 服务商参数配置
        </el-tag>
      </el-divider>

      <el-form ref="isvParamFormModel" :model="ifParams" label-position="top" :rules="ifParamsRules">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="微信支付商户号" prop="mchId">
              <el-input v-model="ifParams.mchId" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用AppID" prop="appId">
              <el-input v-model="ifParams.appId" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用AppSecret" prop="appSecret">
              <el-input v-model="ifParams.appSecret" :placeholder="ifParams.appSecret_ph" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="oauth2地址（置空将使用官方）" prop="oauth2Url">
              <el-input v-model="ifParams.oauth2Url" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信支付API版本" prop="apiVersion">
              <el-radio-group v-model="ifParams.apiVersion" default="V3">
                <el-radio disabled label="V2">V2</el-radio>
                <el-radio label="V3">V3</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="APIv2密钥" prop="key">
              <el-input v-model="ifParams.key" :placeholder="ifParams.key_ph" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="APIv3密钥" prop="apiV3Key">
              <el-input v-model="ifParams.apiV3Key" :placeholder="ifParams.apiV3Key_ph" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="序列号" prop="serialNo">
              <el-input v-model="ifParams.serialNo" :placeholder="ifParams.serialNo_ph" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="API证书(apiclient_cert.p12)" prop="cert">
              <el-input v-model="ifParams.cert" disabled />
              <FileUpload
                :fileUrl="ifParams.cert"
                @success="(response) => uploadSuccess(response.url, 'cert')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="API证书(apiclient_key.pem)" prop="keyPem">
              <el-input v-model="ifParams.keyPem" disabled />
              <FileUpload
                :fileUrl="ifParams.keyPem"
                @success="(response) => uploadSuccess(response.url, 'keyPem')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="API证书(apiclient_cert.pem)" prop="certPem">
              <el-input v-model="ifParams.certPem" disabled />
              <FileUpload
                :fileUrl="ifParams.certPem"
                @success="(response) => uploadSuccess(response.url, 'certPem')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div style="position: absolute; bottom: 0; width: 100%; border-top: 1px solid #e8e8e8; padding: 10px 16px; text-align: right; left: 0; background: #fff; border-radius: 0 0 2px 2px;">
        <el-button style="margin-right: 8px" @click="onClose">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { savePayConfig, req, getIsvPayConfigUnique } from '@/api/pay/isv/IsvPayIfConfigList'
import FileUpload from '@/components/FileUpload'
export default {
  props: {
    callbackFunc: { type: Function, default: () => ({}) }
  },

  components: {
    FileUpload
  },

  data () {
    return {
      btnLoading: false,
      visible: false, // 抽屉开关
      loading: false,
      isAdd: true,
      saveObject: {}, // 保存的对象
      ifParams: { apiVersion: 'V3' }, // 参数配置对象
      rules: {
        ifRate: [{ required: false, pattern: /^(([1-9]{1}\d{0,1})|(0{1}))(\.\d{1,4})?$/, message: '请输入0-100之间的数字，最多四位小数', trigger: 'blur' }]
      },
      ifParamsRules: {
        mchId: [{ required: true, message: '请输入微信支付商户号', trigger: 'blur' }],
        appId: [{ required: true, message: '请输入应用AppID', trigger: 'blur' }],
        appSecret: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.isAdd && !value) {
              callback(new Error('请输入应用AppSecret'))
            }
            callback()
        } }],
        key: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.apiVersion === 'V2' && this.isAdd && !value) {
              callback(new Error('请输入API密钥'))
            }
            callback()
        } }],
        apiV3Key: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.apiVersion === 'V3' && this.isAdd && !value) {
              callback(new Error('请输入API V3秘钥'))
            }
            callback()
        } }],
        serialNo: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.apiVersion === 'V3' && this.isAdd && !value) {
              callback(new Error('请输入序列号'))
            }
            callback()
        } }],
        cert: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.apiVersion === 'V3' && this.isAdd && !value) {
              callback(new Error('请上传API证书(apiclient_cert.p12)'))
            }
            callback()
          } }],
        apiClientCert: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.apiVersion === 'V3' && this.isAdd && !value) {
              callback(new Error('请上传证书文件(apiclient_cert.pem)'))
            }
            callback()
          } }],
        apiClientKey: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.apiVersion === 'V3' && !value) {
              callback(new Error('请上传私钥文件(apiclient_key.pem)'))
            }
            callback()
        } }]
      }
    }
  },
  methods: {
    // 弹层打开事件
    show: function (isvNo, record) {
      if (this.$refs.infoFormModel !== undefined) {
        this.$refs.infoFormModel.resetFields()
      }
      if (this.$refs.isvParamFormModel !== undefined) {
        this.$refs.isvParamFormModel.resetFields()
      }

      // 数据初始化
      this.saveObject = {
        infoId: isvNo,
        ifCode: record.ifCode,
        state: record.ifConfigState === 0 ? 0 : 1
      }

      // 参数配置对象，数据初始化
      this.ifParams = {
        apiVersion: 'V3',
        appSecret: '',
        appSecret_ph: '请输入',
        key: '',
        key_ph: '请输入',
        apiV3Key: '',
        apiV3Key_ph: '请输入',
        serialNo: '',
        serialNo_ph: '请输入'
      }
      this.visible = true
      this.$nextTick(() => {
        this.getIsvPayConfig()
      })
    },
    // 支付参数配置
    getIsvPayConfig () {
      const that = this
      that.loading = true
      // 获取支付参数
      getIsvPayConfigUnique(that.saveObject.infoId, that.saveObject.ifCode)
        .then(res => {
          if (res && res.data && res.data.ifParams) {
            that.saveObject = res.data
            try {
              that.ifParams = JSON.parse(res.data.ifParams)
              that.ifParams.appSecret_ph = that.ifParams.appSecret || '请输入'
              that.ifParams.appSecret = ''
              that.ifParams.key_ph = that.ifParams.key || '请输入'
              that.ifParams.key = ''
              that.ifParams.apiV3Key_ph = that.ifParams.apiV3Key || '请输入'
              that.ifParams.apiV3Key = ''
              that.ifParams.serialNo_ph = that.ifParams.serialNo || '请输入'
              that.ifParams.serialNo = ''
              that.isAdd = false
            } catch (e) {
              console.error('解析配置参数失败:', e)
              that.$message.error('解析配置参数失败')
              that.ifParams = {
                apiVersion: 'V2',
                appSecret: '',
                appSecret_ph: '请输入',
                key: '',
                key_ph: '请输入',
                apiV3Key: '',
                apiV3Key_ph: '请输入',
                serialNo: '',
                serialNo_ph: '请输入'
              }
              that.isAdd = true
            }
          } else {
            that.isAdd = true
          }
        })
        .catch(error => {
          console.error('获取支付配置失败:', error)
          that.$message.error('获取支付配置失败')
          that.isAdd = true
        })
        .finally(() => {
          that.loading = false
        })
    },
    // 表单提交
    onSubmit () {
      const that = this
      this.$refs.infoFormModel.validate(valid => {
        this.$refs.isvParamFormModel.validate(valid2 => {
          if (valid && valid2) { // 验证通过
            that.btnLoading = true
            const reqParams = {}
            reqParams.infoId = that.saveObject.infoId
            reqParams.ifCode = that.saveObject.ifCode
            reqParams.ifRate = that.saveObject.ifRate
            reqParams.state = that.saveObject.state
            reqParams.remark = that.saveObject.remark
            // 支付参数配置不能为空
            if (Object.keys(that.ifParams).length === 0) {
              this.$message.error('参数不能为空！')
              return
            }
            // 脱敏数据为空时，删除该key
            that.clearEmptyKey('appSecret')
            that.clearEmptyKey('key')
            that.clearEmptyKey('apiV3Key')
            that.clearEmptyKey('serialNo')
            reqParams.ifParams = JSON.stringify(that.ifParams)
            // 请求接口
            if (Object.keys(reqParams).length === 0) {
              this.$message.error('参数不能为空！')
              return
            }
            savePayConfig(reqParams.infoId, reqParams.ifCode, reqParams).then(res => {
              that.$message.success('保存成功')
              that.visible = false
              that.btnLoading = false
              that.callbackFunc()
            })
          }
        })
      })
    },
    // 脱敏数据为空时，删除对应key
    clearEmptyKey (key) {
      if (!this.ifParams[key]) {
        this.ifParams[key] = undefined
      }
      this.ifParams[key + '_ph'] = undefined
    },
    // 上传文件成功回调方法，参数value为文件地址，name是自定义参数
    uploadSuccess (value, name) {
      this.ifParams[name] = value
      this.$forceUpdate()
    },
    onClose () {
      this.visible = false
    }
  }
}
</script>
<style lang="less" scoped>
.wxpay-config-drawer {
  .drawer-container {
    padding: 20px;
  }
}

.el-divider {
  margin: 24px 0;
}
</style>
